var express = require('express');
var router = express.Router();
var {query} = require('../utils/db')
var moment = require('moment')

/* 前台网站首页. */
router.get('/',(req,res)=>{
    //1, 栏目数据
    var sql1 = `select * from category where active=1`
    query(sql1,(category)=>{
        var sql2 = `select * from article order by time desc limit 10`
        query(sql2,(article)=>{
            res.render('index/index.ejs',{
                category,
                article,
                cid:0
            })
        })
    })
    // var sql2 = `select * from article `
    // //2, 文章数据
    
})
// 栏目列表页
router.get('/category',(req,res)=>{
    var cid = req.query.cid
    var sql1 = `select * from category where active=1`
    query(sql1,(category)=>{
        var sql2 = `select * from article where cid=${cid} order by time desc`
        query(sql2,(article)=>{
            res.render('index/index.ejs',{
                category,
                article,
                cid
            })
        })
    })
})

//文章详情页
router.get('/article',(req,res)=>{
    var aid = req.query.aid
    var sql = `select * from article where aid=${aid}`
    console.log(sql)
    var sql1 = `select * from category where active=1`
    query(sql1,(category)=>{
        query(sql,(data)=>{
            // [{aid,title}]
            console.log(data)
            var article = data[0]
            var sql3 = `select * from coment where aid=${aid} order by time desc`
            query(sql3,(coment)=>{

                console.log(coment)

                res.render('index/article.ejs',{
                    article:article,
                    cid:article.cid,
                    category:category,
                    aid:aid,
                    coment:coment,
                    moment:moment
                })
            })
        })
    })
    
})

// 评轮功能

router.post('/coment',(req,res)=>{
    console.log(req.body)
    var content = req.body.content
    var aid = parseInt(req.body.aid)
    var time = moment().format('YYYY-MM-DD, h:mm:ss')
    var sql =  `insert into coment (content,aid,time) values ('${content}',${aid},'${time}')`
    console.log(sql)
    query(sql,(data)=>{
        var url = `/article?aid=${aid}`
        res.redirect(url)
    })
})

module.exports = router;
